<!--
  文件描述：图片列表
  创建时间：2023/10/7 10:36
  创建人：二
-->
<template>
  <m-dialog
    :title="title"
    :visible="visible"
    append-to-body
    :loading="loading"
    width="850px"
    @close="close"
  >
    <div class="container">
      <div class="image-group">
        <div class="group-tree">
          <el-tree
            :data="groupTree"
            :props="treeProps"
            node-key="id"
            accordion
            highlight-current
            @node-click="handleNodeClick"
          >
          </el-tree>
        </div>
        <el-button type="text">新增分组</el-button>
      </div>
      <div class="image-main">
        <div class="top-operate">
          <div class="search-form">
            <el-input
              placeholder="搜索图片名称"
              style="width: 200px;margin-right: 15px"
              v-model="queryParam.name"
            />
            <el-button type="primary" @click="handleRefresh(true)">查询</el-button>
          </div>
          <div class="image-upload">
            <span class="upload-desc">
              图片大小不能超过{{ uploadSizeLimit }}M
            </span>
            <el-upload
              ref="upload"
              action="faction"
              :show-file-list="false"
              :http-request="uploadImage"
              :before-upload="beforeUpload"
              :accept="accept">
              <el-button type="primary">
                <i class="el-icon-upload el-icon--left"/>
                点击上传
              </el-button>
            </el-upload>
          </div>
        </div>

        <div class="image-list-body">
          <template v-if="imageList.length">
            <div
              class="image-list"
            >
              <div
                class="image-item"
                v-for="d in imageList"
                :key="d.id"
                :class="{ active: imageActive(d) }"
                @click="onSelectImage(d)"
              >
                <el-image
                  style="width: 95px; height: 95px"
                  fit="contain"
                  :src="d.path"
                />
                <p class="m-line-1 image-name">
                  {{d.name}}
                </p>
                <div class="select-mask">
                  <i class="el-icon-check selected-icon"></i>
                </div>
              </div>
            </div>

            <div class="footer-operate">
              <div class="footer-operate-left" v-show="selectedImageArray.length">
                <span class="footer-desc">已选择{{ selectedImageArray.length }}项</span>
                <el-button-group>
                  <el-button >删除</el-button>
                  <el-button >移动</el-button>
                </el-button-group>
              </div>
              <div class="pagination-wrap">
                <m-pagination
                  layout="prev, pager, next"
                  :total="total"
                  :page-size.sync="queryParam.limit"
                  :current-page.sync="queryParam.page"
                  @pagination-change="handleRefresh()"
                />
              </div>
            </div>

          </template>



          <el-empty v-else-if="!loading"></el-empty>



        </div>

      </div>
    </div>
    <template slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()" :loading="loading">确 定</el-button>
    </template>
  </m-dialog>
</template>

<script>
import {
  imageListApi,
  imageGroupApi
} from '@/api/file/image'
export default {
  name: 'MSelectImageList',
  props: {
    // 多选模式, 如果false为单选
    multiple: {
      type: Boolean,
      default: false
    },
    // 最大选择的数量限制, multiple模式下有效
    maxNum: {
      type: Number,
      default: 100
    },
    // 已选择数量
    selectedNum: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      title: '图片库',
      // 对话框是否可见
      visible: false,
      loading: true,
      // 查询参数
      queryParam: {
        // 文件名称
        name: '',
        // 页码
        page: 1,
        // 每页显示数据
        limit: 15
      },
      // 数据总数
      total: 0,
      // 图片列表
      imageList: [],
      // 分类树形
      groupTree: [],
      // 选中的图片
      selectedImageArray: [],
      // 树形配置
      treeProps: {
        label: 'name'
      },
      // 上传图片大小限制（M）
      uploadSizeLimit: 3,
      // 图片上传的格式限制
      accept: 'image/jpeg,image/png,image/gif,image/webp'
    }
  },
  computed: {
    imageActive() {
      return data => {
        return this.selectedImageArray.findIndex(d => d.id === data.id) !== -1;
      }
    }
  },
  created() {
    this.getImageGroup();
  },
  methods: {
    // 打开
    open() {
      this.visible = true;
      this.handleRefresh(true);
    },
    // 关闭
    close() {
      this.visible = false;
    },
    // 上传图片之前
    beforeUpload(file) {
      // 验证文件大小
      const fileSizeMb = file.size / 1024 / 1024;
      const isImage = file.type.indexOf('image') !== -1;

      if (!isImage) {
        this.$message.error(`只能上传图片格式：${this.accept}!`);
        return false;
      }
      if (fileSizeMb > this.uploadSizeLimit) {
        this.$message.error(`上传的图片大小不能超出${this.uploadSizeLimit}MB`);
        return false;
      }
      return true;
    },
    // 上传图片
    uploadImage(params) {
      const file = params.file;
      console.log('file', file)
    },
    /**
     * 刷新列表
     * @param {Boolean} bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      bool && (this.queryParam.page = 1);
      // 清空选中
      this.selectedImageArray = []
      // 获取文件列表
      this.getImageList()
    },
    // 获取文件列表
    getImageList() {
      this.loading = true;
      imageListApi({
        ...this.queryParam
      }).then(res => {
        this.imageList = res.data.list;
        this.total = res.data.total;
      }).finally(() => {
        this.loading = false;
      })
    },
    // 获取分类
    getImageGroup() {
      imageGroupApi().then(res => {
        this.groupTree = [
          {
            id: -1,
            name: '全部'
          },
          {
            id: 0,
            name: '未分组'
          },
          ...res.data
        ];
      })
    },
    // 图片分组点击
    handleNodeClick() {
      this.handleRefresh(true);
    },
    // 选中图片
    onSelectImage(data) {
      const { multiple, maxNum, selectedImageArray } = this;
      // 单选
      if (!multiple) {
        this.selectedImageArray = [data]
        return;
      }

      let index = selectedImageArray.findIndex(d => d.id === data.id);

      // 是否已经选中
      let selected = index !== -1;

      // 验证数量限制
      if (!selected && (selectedImageArray.length + this.selectedNum) >= maxNum) {
        this.$message({
          message: `最多可选${maxNum}个文件`,
          type: 'warning'
        })
        return;
      }
      // 如果已选中就删除，未选中就添加
      selected ?  selectedImageArray.splice(index, 1) : selectedImageArray.push(data);

    },
    // 确定
    handleSubmit() {
      // 通知父端组件提交完成了
      this.$emit('handleSubmit', this.selectedImageArray)
      // 关闭对话框
      this.close();
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    display: flex;
    height: 380px;
    .image-group,
    .image-main {
      display: flex;
      flex-direction: column;
      height: 100%;
    }

    .image-group {
      flex: 1;
      margin-right: 20px;
      border-right: 1px solid rgba(0, 0, 0, 0.05);
      display: flex;
      flex-direction: column;
      .group-tree {
        flex: 1;
      }
    }

    .image-main {
      width: 630px;
      .top-operate {
        display: flex;
        margin-bottom: 10px;

        .image-upload {
          flex: 1;
          display: flex;
          justify-content: right;
          align-items: center;

          .upload-desc {
            font-size: 12px;
            padding-right: 10px;
            color: #999;
          }
        }
      }
      .image-list-body {
        flex: 1;
        display: flex;
        flex-direction: column;

        .image-list {
          flex: 1;

          .image-item {
            width: 110px;
            position: relative;
            cursor: pointer;
            border-radius: 2px;
            padding: 4px;
            border: 1px solid rgba(0, 0, 0, 0.05);
            float: left;
            margin: 8px;
            -webkit-transition: All 0.2s ease-in-out;
            -moz-transition: All 0.2s ease-in-out;
            -o-transition: All 0.2s ease-in-out;
            transition: All 0.2s ease-in-out;
            &:hover {
              border: 1px solid #16bce2;
            }

            .image-name {
              font-size: 12px;
              text-align: center;
            }

            // 遮罩层(选中时)
            &.active .select-mask {
              display: block;
            }
            .select-mask {
              display: none;
              position: absolute;
              top: 0;
              bottom: 0;
              left: 0;
              right: 0;
              background: rgba(0, 0, 0, 0.41);
              text-align: center;
              border-radius: 2px;
              .selected-icon {
                font-size: 26px;
                color: #fff;
                line-height: 122px;
                text-align: center;
              }
            }

          }

        }

        .footer-operate {
          overflow: hidden;
          margin-top: 15px;
          .footer-operate-left {
            float: left;
            .footer-desc {
              margin-right: 10px;
            }
          }
          .pagination-wrap {
            float: right;
            :deep(.m-pagination) {
              margin: 0;
            }
          }
        }
      }
    }

  }
</style>
